const colors = require("colors/safe")
const crypto = require('crypto')
const {SUCCESS} = require("../enumeration/code")
module.exports = {
  uuid(len) {
    let str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJkLMNOPQRSTUVWXYZ0123456789"
    let chars = []
    for (let i = 0; i < len; i++) {
      //随机生成一个位置
      let pos = Math.floor(Math.random() * str.length)
      chars.push(str[pos])
    }
    return chars.join("").toLocaleLowerCase()
  },
  random() {
    // 生成随机字符串
    let randomStr = Number('' + Math.ceil(Math.random() * 1000) + Date.now()).toString(36) + Math.random().toString(36).slice(2)
    return randomStr
  },
  signature(data) {
    let hash = crypto.createHash('sha256')
    hash.update(data)
    return hash.digest("hex").slice(5, 25)
  },
  getUserInfo(token) {
    let rdb = process.rdb
    return new Promise(resolve => {
      rdb.get(token, (err, res) => {
        resolve(JSON.parse(res))
      })
    })
  },
  result(data = null, msg = "", code = SUCCESS) {
    if (!data) data = null
    if (!msg) msg = ""
    return {
      data,
      msg,
      code
    }
  },
  logger(info) {
    info = info.toString()
    let warn = () => {
      console.log(colors.yellow(info))
    }
    let success = () => {
      console.log(colors.green(info))
    }
    let error = () => {
      console.log(colors.red("info"))
    }

    return {
      warn,
      success,
      error
    }

  }
}
